package com.hushui.mall.commodity.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.hushui.common.to.SkuHasStockVo;
import com.hushui.common.to.es.SkuEsModel;
import com.hushui.common.utils.R;
import com.hushui.mall.commodity.entity.*;
import com.hushui.mall.commodity.entity.vo.SpuVo;
import com.hushui.mall.commodity.feign.SearchFeignServic;
import com.hushui.mall.commodity.feign.WareFeignService;
import com.hushui.mall.commodity.service.*;
import com.hushui.mall.commodity.utils.ProductStatus;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hushui.common.utils.PageUtils;
import com.hushui.common.utils.Query;

import com.hushui.mall.commodity.dao.SpuInfoDao;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;


@Service("spuInfoService")
@Slf4j
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
     private CategoryBrandRelationService service;
    @Resource
    BrandService brandService;
    @Resource
    CategoryService categoryService;
    @Resource
    ProductAttrValueService productAttrValueService;
    @Resource
    WareFeignService wareFeignService;
    @Resource
    SearchFeignServic searchFeignServic;
    @Resource
    SkuInfoService skuInfoService;
    @Resource
    AttrService attrService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils querySpuPage(Map<String, Object> params, Long brandId, Integer status,Long catelogId) {
        if(brandId == 0 && status == 0 && catelogId == 0){
            IPage<SpuInfoEntity> page = this.page(new Query<SpuInfoEntity>().getPage(params), new QueryWrapper<>());
            IPage<SpuVo> convert = page.convert(result -> {
                SpuVo spuVo = new SpuVo();
                BeanUtils.copyProperties(result, spuVo);
                QueryWrapper<CategoryBrandRelationEntity> queryWrapper = new QueryWrapper<CategoryBrandRelationEntity>().eq("brand_id", spuVo.getBrandId()).eq("catelog_id", spuVo.getCatalogId());
                CategoryBrandRelationEntity one = service.getOne(queryWrapper);
                spuVo.setBrandName(one.getBrandName());
                spuVo.setCatalogName(one.getCatelogName());
                return spuVo;
            });
            return new PageUtils(convert);
        }else {
            String key = (String)params.get("key");
            QueryWrapper<SpuInfoEntity> wrapper = new QueryWrapper<>();
            wrapper.eq("brand_id",brandId).eq("publish_status",status);
            IPage<SpuInfoEntity> page=this.page(new Query<SpuInfoEntity>().getPage(params),wrapper);
            IPage<SpuVo> convert = page.convert(result -> {
                SpuVo spuVo = new SpuVo();
                BeanUtils.copyProperties(result, spuVo);
                QueryWrapper<CategoryBrandRelationEntity> queryWrapper = new QueryWrapper<CategoryBrandRelationEntity>().eq("brand_id", spuVo.getBrandId()).eq("catelog_id", spuVo.getCatalogId());
                CategoryBrandRelationEntity one = service.getOne(queryWrapper);
                spuVo.setBrandName(one.getBrandName());
                spuVo.setCatalogName(one.getCatelogName());
                return spuVo;
            });
            if (!StringUtils.isEmpty(key)){
                List<SpuVo> records = convert.getRecords();
                Iterator<SpuVo> iterator = records.iterator();
                while (iterator.hasNext()){
                    SpuVo next = iterator.next();
                    if (!next.getBrandName().contains(key) && !next.getCatalogName().contains(key) && !next.getCatalogId().toString().equals(key) && !next.getBrandId().toString().equals(key) && !next.getSpuDescription().contains(key)){
                        iterator.remove();
                        convert.setTotal(convert.getTotal()-1);
                }
            };
            }
            return new PageUtils(convert);
        }
    }

    @Override
    public boolean up(Long spuId) {
//1.查当前spuid的sku信息
//        List<SkuInfoEntity> sku_ids = skuInfoService.list(new QueryWrapper<SkuInfoEntity>().eq("spu_id", spuId));
//        //查询当前spu的规格属性
//        List<AttrEntity>attrEntities=productAttrValueService.findAttrBySpuId(spuId);
////        List<SkuEsModel.Attrs> collect = attrEntities.stream().map(attrEntity -> {
////            SkuEsModel.Attrs attrs = new SkuEsModel.Attrs();
////            BeanUtil.copyProperties(attrEntity, attrs);
////            attrs.setAttrValue(attrEntity.getValueSelect());
////            return attrs;
////        }).collect(Collectors.toList());
//        List<ProductAttrValueEntity> baseAttrs = productAttrValueService.baseAttrListforspu(spuId);
//        List<Long> collect1 = sku_ids.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());
//        final  Map<Long,Boolean> map= new HashMap<>();
//        try {
//            R r = wareFeignService.getSkuHasStock(collect1);
//            Object data = r.get("data");
//            log.info("ObjectToString+{}",data.toString());
//            log.info("JsonToString+{}", JSON.toJSON(data).toString());
//
//            List<SkuStockTo> skuStockTos = JSON.parseArray(JSON.toJSON(data).toString(), SkuStockTo.class);
//
//            skuStockTos.stream().forEach(skuStock-> {
//                map.put(skuStock.getSkuId(),skuStock.getHasStock());
//            });
//        } catch (Exception e) {
//            throw new RuntimeException("远程调用库存方法失败，失败原因+"+e.getMessage());
//        }
//        List<SkuEsModel> skuEsModels = sku_ids.stream().map(sku -> {
//            SkuEsModel skuEsModel = new SkuEsModel();
//            BeanUtil.copyProperties(sku, skuEsModel);
//            //skuPrice,skuImg,
//            skuEsModel.setSkuPrice(sku.getPrice());
//            skuEsModel.setSkuImg(sku.getSkuDefaultImg());
//
//            //brandName,brandImg,catalogName
//            BrandEntity brand = brandService.getById(sku.getBrandId());
//            CategoryEntity category = categoryService.getById(sku.getCatalogId());
//            skuEsModel.setBrandName(brand.getName());
//            skuEsModel.setBrandImg(brand.getLogo());
//            skuEsModel.setCatalogName(category.getName());
//            skuEsModel.setAttrs(collect);
//            //远程查库存系统是否有库存
//            skuEsModel.setHotScore(0L);
//            if(map==null){
//                skuEsModel.setHasStock(false);
//            }
//            skuEsModel.setHasStock(map.get(sku.getSkuId()));
//            return skuEsModel;
//        }).collect(Collectors.toList());
//        //调用检索服务实现上架服务
//        try {
//            R r = searchFeignServic.productUp(skuEsModels);
//        } catch (Exception e) {
//            log.info("远程调用上架服务失败{}", e);
//            return  false;
//        }
//        //调整spu的上架状态
//        baseMapper.updateStatus(spuId, ProductStatus.PRODUCT_UP_STATUS.getCode());
//        return true ;

        //1、查出当前spuId对应的所有sku信息,品牌的名字
        List<SkuInfoEntity> skuInfoEntities = skuInfoService.getSkusBySpuId(spuId);

        //查出当前sku的所有可以被用来检索的规格属性
        List<ProductAttrValueEntity> baseAttrs = productAttrValueService.baseAttrListforspu(spuId);

        List<Long> attrIds = baseAttrs.stream().map(attr -> {
            return attr.getAttrId();
        }).collect(Collectors.toList());

        List<Long> searchAttrIds = attrService.selectSearchAttrs(attrIds);
        //转换为Set集合
        Set<Long> idSet = searchAttrIds.stream().collect(Collectors.toSet());

        List<SkuEsModel.Attrs> attrsList = baseAttrs.stream().filter(item -> {
            return idSet.contains(item.getAttrId());
        }).map(item -> {
            SkuEsModel.Attrs attrs = new SkuEsModel.Attrs();
            BeanUtils.copyProperties(item, attrs);
            return attrs;
        }).collect(Collectors.toList());

        List<Long> skuIdList = skuInfoEntities.stream()
                .map(SkuInfoEntity::getSkuId)
                .collect(Collectors.toList());
        //发送远程调用，库存系统查询是否有库存
        Map<Long, Boolean> stockMap = null;
        try {
            R skuHasStock = wareFeignService.getSkuHasStock(skuIdList);
            //
            TypeReference<List<SkuHasStockVo>> typeReference = new TypeReference<List<SkuHasStockVo>>() {};
            stockMap = skuHasStock.getData(typeReference).stream()
                    .collect(Collectors.toMap(SkuHasStockVo::getSkuId, item -> item.getHasStock()));
        } catch (Exception e) {
            log.error("库存服务查询异常：原因{}",e);
        }

        //2、封装每个sku的信息
        Map<Long, Boolean> finalStockMap = stockMap;
        List<SkuEsModel> collect = skuInfoEntities.stream().map(sku -> {
            //组装需要的数据
            SkuEsModel esModel = new SkuEsModel();
            esModel.setSkuPrice(sku.getPrice());
            esModel.setSkuImg(sku.getSkuDefaultImg());

            //设置库存信息
            if (finalStockMap == null) {
                esModel.setHasStock(true);
            } else {
                esModel.setHasStock(finalStockMap.get(sku.getSkuId()));
            }

            //热度评分。0
            esModel.setHotScore(0L);

            //查询品牌和分类的名字信息
            BrandEntity brandEntity = brandService.getById(sku.getBrandId());
            esModel.setBrandName(brandEntity.getName());
            esModel.setBrandId(brandEntity.getBrandId());
            esModel.setBrandImg(brandEntity.getLogo());

            CategoryEntity categoryEntity = categoryService.getById(sku.getCatalogId());
            esModel.setCatalogId(categoryEntity.getCatId());
            esModel.setCatalogName(categoryEntity.getName());

            //设置检索属性
            esModel.setAttrs(attrsList);

            BeanUtils.copyProperties(sku,esModel);

            return esModel;
        }).collect(Collectors.toList());

        //将数据发给es进行保存
        R r = searchFeignServic.productUp(collect);

        if (r.getCode() == 0) {
            //远程调用成功
            //TODO 6、修改当前spu的状态
            baseMapper.updateStatus(spuId, ProductStatus.PRODUCT_UP_STATUS.getCode());
        } else {
            //远程调用失败
            //TODO 7、重复调用？接口幂等性:重试机制
        }
        return true ;
    }

}